﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Deployment.Compression;
using Microsoft.Deployment.Compression.Cab;
using Microsoft.Deployment.Resources;


using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;

namespace Infopath_XSF_WinForm
{
    public partial class Form1 : Form
    {
        private const string OK = "OK";
        private const string ERROR = "ERROR";
        public string strFilename, docText;
        public string currentdir,dirtemp;


        public Form1()
        {
            InitializeComponent();
        }
    

        private void button1_Click(object sender, EventArgs e)
        {

            DialogResult result = openFileDialog1.ShowDialog();
            string pathxsn = string.Empty;

            if (result == DialogResult.OK) // Test result.
            {
                pathxsn = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
                lblxsnetat.Text = OK;
                lblxsnetat.ForeColor = Color.FromName("green");
                txtxsn.Text = pathxsn;


                /*COPIE DE XSN et CAB*/
                string pathxsncopy = pathxsn;
                FileCopy(pathxsn, pathxsncopy);

                /*EXTRACT CAB -> TEMP*/
                CabExtract(pathxsn);

            }
            else {
                lblxsnetat.Text = ERROR;
                lblxsnetat.ForeColor = Color.FromName("red");
            }


        }
        private void FileCopy(string path,string path2)
        {
             try 
                {
                    path2 = Path.ChangeExtension(path, ".cab");
                  
                    // Ensure that the target does not exist.
                    File.Delete(path2);

                    // Copy the file.
              
                    File.Copy(path, path2);
                    
                    lblcopie.Text = OK;
                    lblcopie.ForeColor = Color.FromName("green");
                

                    // Try to copy the same file again, which should succeed.
                   File.Copy(path, path2, true);
                    
                  
                   


                } 

                catch 
                {
                    lblcopie.Text = ERROR;
                    lblcopie.ForeColor = Color.FromName("red");
                    MessageBox.Show("The double copy is not allowed");
                }
        }

        private void CabExtract(string path)
        {
            /*EXTRACT CAB*/
            path=Path.ChangeExtension(path, ".cab");
            string dir =Path.GetDirectoryName(path);
            currentdir = dir;
            dir = dir + "\\temp";
            dirtemp = dir;
            try
            {
               
                EnsureDirectoryExists(dir);
                var cabToUnpack = new CabInfo(path);
                cabToUnpack.Unpack(dir);
               
                lblcab.Text = OK;
                lblcab.ForeColor = Color.FromName("green");
                openXSF(dir+"\\manifest.xsf");
                

            }
            catch (CabException ex)
            {
                lblcab.Text = ERROR;
                lblcab.ForeColor = Color.FromName("red");
                MessageBox.Show("Unable to extract the Cab File", ex.ToString());
            }
        }
        private void CabPack()
        {
            try
            {
                var cabToPack = new CabInfo(currentdir + "\\FormulaireUpdate.cab");
                var sourceDir = currentdir;//temp
                cabToPack.Pack(sourceDir, true, Microsoft.Deployment.Compression.CompressionLevel.Max, null);

                string path = currentdir + "\\FormulaireUpdate.cab";
                string path2 = Path.ChangeExtension(path, ".xsn");

                File.Copy(path, path2);
             
            }
            catch (CabException ex)
            {
                MessageBox.Show("Unable to recreact the CAB file"+ex.ToString());
            }
        }
        private static void EnsureDirectoryExists(string dir)
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }

        private void openXSF(string url)
        {
            
            strFilename = url as string;

            if (File.Exists(strFilename))
            {
                
                using (StreamReader sr = new StreamReader(strFilename))
                {
                    docText = sr.ReadToEnd();

                }

                lblman.Text = OK;
                lblman.ForeColor = Color.FromName("green");
        

            }
            else
            {
                lblman.Text = ERROR;
                lblman.ForeColor = Color.FromName("red");
                MessageBox.Show("The MANIFEST " + strFilename + "could not be open");
                
            }

           
        }


        public  void SearchAndReplace(string strFilename, string docText, string searchtext,string searchtext2, string replacetext,string replacetext2)
        {
     
            Regex regexText = new Regex(searchtext);
            Regex regexText2 = new Regex(searchtext2);
            
            docText = regexText.Replace(docText, replacetext);
            docText = regexText2.Replace(docText, replacetext2);

            using (StreamWriter sw = new StreamWriter(strFilename))
            {
                sw.Write(docText);
                /*Clear*/
                txtsiteold.Text = "";
                txtsubsiteold.Text = "";
                txtsitenew.Text = "";
                txtsubsitenew.Text = "";
             
            }

        }
        private void ReplacePublishURL(string strFilename,string namexsn)
        {
            var doc = XDocument.Load(strFilename);//manifest
            doc.Root.Attribute("publishUrl").Value =currentdir+"\\"+namexsn; //temp
            doc.Save(strFilename);

           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txtsiteold.Text != string.Empty && txtsubsiteold.Text != string.Empty)
            {
                SearchAndReplace(strFilename, docText, txtsiteold.Text, txtsubsiteold.Text, txtsitenew.Text, txtsubsitenew.Text);
                ReplacePublishURL(strFilename,txtxsnfield.Text);
                CreateDFF();
             
            }
            else {
                MessageBox.Show("Fill the two Fields");
            
            }
            
             

        }

        private void CreateDFF()
        {
            string path =currentdir+"\\config.ddf";

            string[] fileinside = Directory.GetFiles(dirtemp, "*.*");


            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine(".OPTION EXPLICIT");
                    sw.WriteLine(".Set CabinetNameTemplate=NewTemplateInfoPath.XSN");
                    sw.WriteLine(".set DiskDirectoryTemplate="+currentdir);
                    sw.WriteLine(".Set Cabinet=on");
                    sw.WriteLine(".Set Compress=on");


                    foreach (string item in fileinside)
                    { sw.WriteLine("\"" + item.ToString() + "\""); }



                }
            }

            CreateXSN();

            
            
            
         
        }

        private void CreateXSN()
        {
            Process proc = new Process();
            proc.StartInfo = new ProcessStartInfo("makecab.exe", "/f config.ddf");
            proc.StartInfo.WorkingDirectory = currentdir;
            proc.Start();  
        }
    }
}
